package com.zboot.comm.redis.configure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 二进制序列化
 */
@Slf4j
public class ByteSerializer<T> implements RedisSerializer<T> {

    private Class<T> clazz;

    public ByteSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    /**
     * 序列化
     *
     * @return
     */
    @Override
    public byte[] serialize(T t) {
        if(t==null){
            return new byte[0];
        }
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 反序列化
     *
     * @param bytes
     * @return
     */
    @Override
    public T deserialize(byte[] bytes) {
        if(bytes==null || bytes.length<=0){
            //log.error("redis deserialize bytes为空");
            return null;
        }
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return (T) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Class<?> getTargetType() {
        return this.clazz;
    }
}
